package com.mangguo.tingjian.content.controller;

import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.content.dto.*;
import com.mangguo.tingjian.content.service.IContentDataService;
import com.mangguo.tingjian.content.service.IUserSubscriptionService;
import com.mangguo.tingjian.util.ArraySplitUtils;
import com.mangguo.tingjian.util.CvsUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@RestController
@RequestMapping("/content/data")
@AllArgsConstructor
@Slf4j
public class

ContentDataController {

    private final IContentDataService contentDataService;

    private final IUserSubscriptionService userSubscriptionService;

    private final ExecutorService executorService = new ThreadPoolExecutor(50, 300,
            5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());


    @GetMapping("/audio/simple/{start}/{end}")
    public Result<ContentDataAudioResult> getSimpleForAudio(@PathVariable("start") Integer start,
                                                            @PathVariable("end") Integer end,
                                                            @RequestParam("audioName") String audioName,
                                                            @RequestParam("albumName") String albumName){

        if(audioName.equals("")){
            audioName = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }
        if(audioName != null || albumName != null){
            Long audioId = contentDataService.getAudioIdByAudioNameAndAlbumName(audioName, albumName);
            if (audioId == null){
                return Result.error("音频不存在或者音频与专辑不匹配");
            }
            ContentDataAudioResult contentDataAudioResult = contentDataService.getSimpleForAudio(audioId, start, end);
            if(contentDataAudioResult.getListenMostTimeInt() != null){
                contentDataAudioResult.setListenMostTime(contentDataAudioResult.getListenMostTimeInt() + ":00-"+ (contentDataAudioResult.getListenMostTimeInt() + 1) +":00");
            }
            return Result.success(contentDataAudioResult);
        }else{
            return Result.error("音频输入为空");
        }

    }

    @GetMapping("/audio/table/{start}/{end}")
    public Result<List<ContentDataAudioTableResult>> getTableDataForAudio(@PathVariable("start") Integer start,
                                                                          @PathVariable("end") Integer end,
                                                                          @RequestParam("audioName") String audioName,
                                                                          @RequestParam("albumName") String albumName){
        if(audioName.equals("")){
            audioName = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }
        if(audioName == null){
            return Result.success(null);
        }

        Long audioId = contentDataService.getAudioIdByAudioNameAndAlbumName(audioName, albumName);
        if (audioId == null){
            return Result.success(null);
        }
        return Result.success(contentDataService.getTableDataForAudio(audioId, audioName, start, end));
    }

    @GetMapping("/audio/table/download/{start}/{end}")
    public Result<Void> getTableDataForAudioDownLoad(@PathVariable("start") Integer start,
                                              @PathVariable("end") Integer end,
                                              @RequestParam("audioName") String audioName,
                                              @RequestParam("albumName") String albumName,
                                             HttpServletResponse response){
        if(audioName.equals("")){
            audioName = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }
        if(audioName == null){
            return Result.error("音频输入为空");
        }

        Long audioId = contentDataService.getAudioIdByAudioNameAndAlbumName(audioName, albumName);
        if (audioId == null){
            return Result.error("音频不存在或者音频与专辑不匹配");
        }
        List<ContentDataAudioTableResult> contentDataAudioTableResults = contentDataService.getTableDataForAudio(audioId, audioName, start, end);
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("播放时间", "播放名称", "APP播放量", "H5播放量", "总播放量","APP收听人数","H5收听人数", "总收听人数", "播放率", "点赞数", "分享数", "评论数"));
        for(ContentDataAudioTableResult result : contentDataAudioTableResults){
            list.add(Arrays.asList(Integer.valueOf(result.getDate()).toString(),
                    result.getAudio(),
                    Long.valueOf(result.getAppPlayCount()).toString(),
                    Long.valueOf(result.getH5PlayCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Long.valueOf(result.getAppPeopleCount()).toString(),
                    Long.valueOf(result.getH5PeopleCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Double.valueOf(result.getPlayAvg()).toString(),
                    Long.valueOf(result.getLikeCount()).toString(),
                    Long.valueOf(result.getShareCount()).toString(),
                    Long.valueOf(result.getCommentCount()).toString()));
        }
        CvsUtils.downloadCvs(response, "音频明细表", list);
        return Result.success();
    }


    @GetMapping("/album/simple/{start}/{end}")
    public Result<ContentDataAlbumResult> getSimpleForAblum(@PathVariable("start") Integer start,
                                                            @PathVariable("end") Integer end,
                                                            @RequestParam("cmo") String cmo,
                                                            @RequestParam("albumName") String albumName){

        if(cmo.equals("")){
            cmo = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }

        if(cmo != null || albumName != null){
            List<Long> audioIds = contentDataService.getAudioIdByAlbumNameAndCmo(albumName, cmo);
            if (audioIds == null || audioIds.size() == 0){
                return Result.error("专辑不存在或者生产机构与专辑不匹配");
            }
            Long albumId = contentDataService.getAlbumIdByAlbumNameAndCmo(albumName, cmo);
            ContentDataAlbumResult contentDataAlbumResult = contentDataService.getSimpleForAlbum(audioIds, albumId ,start, end);
            if(contentDataAlbumResult.getListenMostTimeInt() != null){
                contentDataAlbumResult.setListenMostTime(contentDataAlbumResult.getListenMostTimeInt() + ":00-"+ (contentDataAlbumResult.getListenMostTimeInt() + 1) +":00");
            }
            return Result.success(contentDataAlbumResult);
        }else {
            return Result.error("专辑输入为空");
        }

    }

    @GetMapping("/author/simple/{start}/{end}")
    public Result<ContentDataAuthorResult> getSimpleForAblum(@PathVariable("start") Integer start,
                                                             @PathVariable("end") Integer end,
                                                             @RequestParam("authorName") String authorName){

        if(authorName.equals("")){
            authorName = null;
        }
        if(authorName != null){
            ContentDataAuthorResult contentDataAuthorResult = contentDataService.getSimpleForAuthor(authorName, start, end);
            if(contentDataAuthorResult.getListenMostTimeInt() != null){
                contentDataAuthorResult.setListenMostTime(contentDataAuthorResult.getListenMostTimeInt() + ":00-"+ (contentDataAuthorResult.getListenMostTimeInt() + 1) +":00");
            }
            return Result.success(contentDataAuthorResult);
        }else {
            return Result.error("主播输入为空");
        }

    }


    @GetMapping("/album/table/{start}/{end}")
    public Result<List<ContentDataAudioTableResult>> getTableDataForAlbum(@PathVariable("start") Integer start,
                                                                          @PathVariable("end") Integer end,
                                                                          @RequestParam("cmo") String cmo,
                                                                          @RequestParam("albumName") String albumName){
        if(cmo.equals("")){
            cmo = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }
        if(cmo == null && albumName == null){
            return Result.success(null);
        }

        List<Long> audioIds = contentDataService.getAudioIdByAlbumNameAndCmo(albumName, cmo);
        if (audioIds == null || audioIds.size() == 0){
            return Result.success(null);
        }

        List<ContentDataAudioTableResult> resultList = new LinkedList<>(contentDataService.getTableDataForAudios(audioIds, start, end));
        return Result.success(resultList);
    }

    @GetMapping("/album/table/download/{start}/{end}")
    public Result<Void> getTableDataForAlbumDownload(@PathVariable("start") Integer start,
                                              @PathVariable("end") Integer end,
                                              @RequestParam("cmo") String cmo,
                                              @RequestParam("albumName") String albumName,
                                             HttpServletResponse response){
        long startTime = System.currentTimeMillis();
        if(cmo.equals("")){
            cmo = null;
        }
        if(albumName.equals("")){
            albumName = null;
        }
        if(cmo == null && albumName == null){
            return Result.error("生产机构与专辑输入为空");
        }

        List<Long> audioIds = contentDataService.getAudioIdByAlbumNameAndCmo(albumName, cmo);
        if (audioIds == null || audioIds.size() == 0){
            return Result.error("专辑不存在或者生产机构与专辑不匹配");
        }

        ArraySplitUtils<Long> arraySplitUtils = new ArraySplitUtils<>();
        System.out.println("splistIds:" + (audioIds.size()));
        List<List<Long>> splistIds = arraySplitUtils.splistList(audioIds, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(splistIds.size());
        List<ContentDataAudioTableResult> resultList = new ArrayList<>();
        splistIds.forEach(ids -> {
            executorService.execute(() ->{
                resultList.addAll(contentDataService.getTableDataForAudios(ids, start, end));
                countDownLatch.countDown();
            });
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("多线程获取数据异常", e);
        }
        System.out.println("end:get----------" + (System.currentTimeMillis()-startTime));
        resultList.sort(Comparator.comparingInt(ContentDataAudioTableResult::getDate));
        System.out.println("end:sort----------" + (System.currentTimeMillis()-startTime));
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("播放时间", "专辑","音频名称", "APP播放量", "H5播放量", "总播放量","APP收听人数","H5收听人数", "总收听人数", "播放率", "点赞数", "分享数", "评论数"));
        for(ContentDataAudioTableResult result : resultList){
            list.add(Arrays.asList(Integer.valueOf(result.getDate()).toString(),
                    result.getAlbum(),
                    result.getAudio(),
                    Long.valueOf(result.getAppPlayCount()).toString(),
                    Long.valueOf(result.getH5PlayCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Long.valueOf(result.getAppPeopleCount()).toString(),
                    Long.valueOf(result.getH5PeopleCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Double.valueOf(result.getPlayAvg()).toString(),
                    Long.valueOf(result.getLikeCount()).toString(),
                    Long.valueOf(result.getShareCount()).toString(),
                    Long.valueOf(result.getCommentCount()).toString()));
        }
        CvsUtils.downloadCvs(response, "音频明细表", list);
        System.out.println("end:end----------" + (System.currentTimeMillis()-startTime));
        return Result.success();
    }


    @GetMapping("/author/table/{start}/{end}")
    public Result<List<ContentDataAuthorTableResult>> getTableDataForAuthor(@PathVariable("start") Integer start,
                                                                          @PathVariable("end") Integer end,
                                                                          @RequestParam("authorName") String authorName){

        if(authorName.equals("")){
            return Result.success(null);
        }

        List<Long> albumIds = contentDataService.getAlbumIdByAuthorName(authorName);

        if (albumIds == null || albumIds.size() == 0){
            return Result.success(null);
        }

        albumIds.remove(0L);

        List<ContentDataAuthorTableResult> resultList = contentDataService.getTableDataForAlbums(albumIds, start, end);

        return Result.success(resultList);
    }

    @GetMapping("/author/table/download/{start}/{end}")
    public Result<Void> getTableDataForAuthorDownload(@PathVariable("start") Integer start,
                                               @PathVariable("end") Integer end,
                                               @RequestParam("authorName") String authorName,
                                              HttpServletResponse response){

        if(authorName.equals("")){
            return Result.error("主播名字为空");
        }

        List<Long> albumIds = contentDataService.getAlbumIdByAuthorName(authorName);
        if (albumIds == null || albumIds.size() == 0){
            return Result.error("该主播不存在");
        }

        albumIds.remove(0L);

        List<ContentDataAuthorTableResult> resultList = contentDataService.getTableDataForAlbums(albumIds, start, end);

        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("播放时间", "专辑", "APP播放量", "H5播放量", "总播放量","总点击数","APP收听人数","H5收听人数", "总收听人数", "播放率", "订阅数"));
        for(ContentDataAuthorTableResult result : resultList){
            list.add(Arrays.asList(Integer.valueOf(result.getDate()).toString(),
                    result.getAlbum(),
                    Long.valueOf(result.getAppPlayCount()).toString(),
                    Long.valueOf(result.getH5PlayCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Long.valueOf(result.getAppPeopleCount()).toString(),
                    Long.valueOf(result.getH5PeopleCount()).toString(),
                    Long.valueOf(result.getAllPlayCount()).toString(),
                    Double.valueOf(result.getPlayAvg()).toString(),
                    Long.valueOf(result.getSubscription()).toString()));
        }
        CvsUtils.downloadCvs(response, "音频明细表", list);
        return Result.success();

    }


    private List<Integer> getBetweenDates(Integer startInt, Integer endInt) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date start = simpleDateFormat.parse(startInt.toString());
        Date end = simpleDateFormat.parse(endInt.toString());
        List<Integer> result = new LinkedList<>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        tempEnd.add(Calendar.DAY_OF_YEAR, 1);
        while (tempStart.before(tempEnd)) {
            result.add(Integer.valueOf(simpleDateFormat.format(tempStart.getTime())));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }
}
